﻿@{
    ViewBag.Title = "File Upload";
    Layout = ((Core.Models.Theme)Session["Theme"]).Layout;
    string BUId = ViewBag.BusinessUnitId.ToString();
    string TagCategoryId = ViewBag.TagCategoryId.ToString();
}

<h2>File Upload</h2>

@using (Html.BeginForm("AjaxUpload", "File", FormMethod.Post, new { @id = "ajaxUploadForm", enctype = "multipart/form-data" }))
{    
    @Html.Hidden("hdnBusinessUnitId", BUId)
    @Html.Hidden("hdnTagCategoryId", TagCategoryId);
    @Html.Hidden("hdnTagId")
    @Html.Hidden("TagIds","")

<table width="90%" cellspacing="0" cellpadding="5" border="0">
<tr>
    <td valign="top">
    <fieldset>
        <legend>File</legend>
        <div class="editor-label">
            @Html.Label("Description")
        </div>
        <div class="editor-field">
            @Html.TextBox("txtDescription", null, new { size = "35" })            
            <span style="color: red" id="valdesc"></span>
        </div>

        <div class="editor-label">
            @Html.Label("File to Upload")
        </div>
        <div class="editor-field">
            <input type="file" name="file" id="file" size="35" /><br />(512KB max size)<span style="color: red" id="valfile"></span>
        </div>
        <br />
    </fieldset>  
    </td>        
    <td valign="top">
    <fieldset>
        <legend>Tags</legend>
        <div class="editor-label">
            @Html.Label("Select Tag")&nbsp;<span style="color: red" id="valtag"></span>
        </div>
        <div class="editor-field">
            @Html.TextBox("txtTag")
            <input type="button" name="TagAdd" value="Add" onclick="javascript: AddTag();" />
            <div id="txtTags" class="AutoCompleteResults"></div>
        </div>
    </fieldset>
    </td>
</tr>
<tr>
    <td colspan="2">
    &nbsp;
    </td>
</tr>
<tr>
    <td colspan="2">
        <input id="ajaxUploadButton" type="submit" value="Upload" /> | 
        @Html.ActionLink("Back to File Manager", "Index", new { id = BUId })
    </td>
</tr>
</table>
}
<div id="uplresult"></div>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery.form.js")" language="javascript"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery.blockUI.js")" language="javascript"></script>
<script type="text/javascript" language="javascript">
    $(function () {
        $("#ajaxUploadForm").ajaxForm({
            iframe: true,
            dataType: "json",
            beforeSubmit: function () {
                var retval = true;
                var v = $("#txtDescription").val();
                if (v == null || v == "") {
                    $("#valdesc").html("&nbsp;Required");
                    retval = false;
                }
                else {
                    $("#valdesc").html("");
                }
                v = $("#TagIds").val();
                if (v == null || v == "") {
                    $("#valtag").html("(Atleast 1 tag is required.)");
                    retval = false;
                }
                else {
                    $("#valtag").html("");
                }
                v = $("#file").val();
                if (v == null || v == "") {
                    $("#valfile").html("&nbsp;Required");
                    retval = false;
                }
                else {
                    var ext = v.substring(v.indexOf('.')).toLowerCase();
                    if (ext != ".txt" && ext != ".gif" && ext != ".jpg" && ext != ".png" && ext != ".pdf" && ext != ".doc" && ext != ".docx" && ext != ".xls" && ext != ".xlsx") {
                        $("#valfile").html("<br />Only file of type .txt, .gif, .jpg, .png, .pdf, .doc, .docx, .xls, .xlsx is accepted.");
                        retval = false;
                    }
                    else {
                        $("#valfile").html("");
                    }
                }
                if (!retval) return false;
                $("#ajaxUploadForm").block({ message: '<div style="font-weight: bold;padding:5px;vertical-align: middle"><img src="/Content/Images/busy.gif" /> Uploading file...</div>' });
            },
            success: function (result) {
                $("#ajaxUploadForm").unblock();
                if (result.message == "Error, File is too large.") {
                    $("#valfile").html("<br />" + result.message);
                }
                else {
                    $("#ajaxUploadForm").resetForm();
                    $("#TagIds").val("");
                    $("#txtTags").html("");
                    var t = $("#uplresult").html();
                    t += "<br />" + result.message;
                    $("#uplresult").html(t);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                $("#ajaxUploadForm").unblock();
                $("#ajaxUploadForm").resetForm();
                var t = $("#uplresult").html();
                t += "<br />Error uploading file";
                $("#uplresult").html(t);
            }
        });
    });
</script>
<script type="text/javascript" language="javascript">
    function RemoveTag(id) {
        // Remove from the comma separated TagIds hidden field
        var ids = $("#TagIds").val();
        var i = ids.toLowerCase().indexOf(id);
        if (i) {
            i -= 1;
            ids = ids.substring(0, i) + ids.substring(i + 37);
            $("#TagIds").val(ids);
        }
        // Remove from the User Interface
        ids = $("#txtTags").html();
        i = ids.toLowerCase().indexOf(id);
        if (i) {
            var t = ids.substring(0, i).toLowerCase();
            var j = t.toLowerCase().lastIndexOf("&nbsp;&lt;<span>");
            ids = ids.substring(0, j) + ids.substring(i + 56);
            $("#txtTags").html(ids);
        }
    }

    function AddTag() {
        // Add in the user interface div. If the below formatting is changed, it needs to reflect in the UserController as well.
        if ($("#hdnTagId").val() != "") {
            var t = "&nbsp;&lt;<span>" + $("#txtTag").val() + "&nbsp;<a href='javascript: RemoveTag(\"" + $("#hdnTagId").val() + "\")'>X</a></span>&gt;";
            var x = $("#txtTags").html();
            x += t;
            $("#txtTags").html(x);
            // Add the id in the hidden hdnTagIds field. The id is placed in the hdnTagId field by the autocomplete select function.
            // Leading comma is used by design for consistency.
            var ids = $("#TagIds").val();
            ids += "," + $("#hdnTagId").val()
            $("#TagIds").val(ids);
            // clear out user input area
            $("#txtTag").val("");
            $("#hdnTagId").val("");
        }
    }

    $(function () {
        $("#txtTag")
        .autocomplete({
            select: function (event, ui) {
                $("#hdnTagId").val(ui.item.id);
            },
            source: function (request, response) {
                $.ajax({
                    url: "/File/Tags", type: "POST", dataType: "json",
                    data: { search: request.term, maxitems: 10, TagCategoryId: $("#hdnTagCategoryId").val() },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name, value: item.Name, id: item.Id }
                        }))
                    }
                })
            }
        });
    });
</script>
